﻿using SuperX.Common.BasicService;
using SuperX.Common;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using SuperX.Common.AppConfiguration;
using SqlSugar;

namespace SuperX.ORM
{
    public class DBClient
    {
        private IProject _project = BasicServiceManager.GetProjService().Project;
        private string _defalutConnectstr = "server=localhost;Port=3306;Database='{0}';Uid=root;Pwd=Mm123456;SslMode=none;charset=utf8mb4;Old Guids=true;allowPublicKeyRetrieval=true";

        private DatabaseProvider _dbType;
        private string _connectionString;

        public DBClient()
        {
            _dbType = SystemCfgService.GetInstance().SystemCfg.CacheDbType;
        }

        public SqlSugarClient CreateClient()
        {
            string ConnectionString = string.Empty;
            DbType dbType = DbType.Sqlite;
            //默认用Sqlite
            if (_dbType == DatabaseProvider.Sqlite)
            {
                ConnectionString = CreateSqliteDB("IOT");
            }
            else
            {
                //其他用MySql
                ConnectionString = string.Format(_defalutConnectstr, "IOT");
                dbType = DbType.MySql;
            }
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = dbType,
                ConnectionString = ConnectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            return Db;
        }

        public SqlSugarClient GetClient()
        {
            string ConnectionString = string.Empty;
            DbType dbType = DbType.Sqlite;
            if (_dbType == DatabaseProvider.Sqlite)
            {
                ConnectionString = CreateSqliteDB("IOT");
            }
            else
            {
                ConnectionString = string.Format(_defalutConnectstr, "IOT");
                dbType = DbType.MySql;
            }
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = dbType,
                ConnectionString = ConnectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            return Db;
        }

        public SqlSugarClient CreateClient(string dbName = "IOT")
        {
            string ConnectionString = string.Empty;
            DbType dbType = DbType.Sqlite;
            if (_dbType == DatabaseProvider.Sqlite)
            {
                ConnectionString = CreateSqliteDB(dbName);
            }
            else
            {
                ConnectionString = string.Format(_defalutConnectstr, dbName);
                dbType = DbType.MySql;
            }
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConnectionString,
                DbType = dbType,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            return Db;
        }

        /// <summary>
        /// 检查Sqlite文件是否存在，不存在先创建再返回连接字符串
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        private string CreateSqliteDB(string dbName)
        {
            string ConnectionString;
            var runtime = Path.Combine(_project.ProjectDir, "Runtime");
            if (!Directory.Exists(runtime)) Directory.CreateDirectory(runtime);
            var path = Path.Combine(_project.ProjectDir, "Runtime", $"{dbName}.db");
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            ConnectionString = $"Data Source={path};";
            return ConnectionString;
        }

        /// <summary>
        /// 创建并初始化DB
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="pathAddress"></param>
        /// <returns></returns>
        public SqlSugarClient CreateClientByCustom<T>(string dbName, string pathAddress = "Runtime")
        {
            var runtime = Path.Combine(_project.ProjectDir, pathAddress);
            if (!Directory.Exists(runtime)) Directory.CreateDirectory(runtime);
            var path = Path.Combine(_project.ProjectDir, pathAddress, $"{dbName}.db");
            if (!File.Exists(path)) File.Create(path).Close();
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = $"Data Source={path};",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            Db.CodeFirst.SetStringDefaultLength(50);
            Db.DbMaintenance.CreateDatabase();
            Db.CodeFirst.InitTables<T>();
            return Db;
        }

        public void InitDatabase()
        {
            var db = CreateClient();
            db.CodeFirst.SetStringDefaultLength(50);
            db.DbMaintenance.CreateDatabase();
        }

        public void InitTable<T>()
        {
            var db = CreateClient();
            db.CodeFirst.InitTables<T>();
        }

        public void InitTable<T>(SqlSugarClient db)
        {
            db.CodeFirst.InitTables<T>();
        }

        public SqlSugarClient GetMysqlClient()
        {
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = $"server=192.168.10.31;Database=IOT;Uid=root;Pwd=superx@2023;charset=utf8;",
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            return Db;
        }
    }
}